<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>渐进学习平台 - 练习系统</title>
  <style>
    /* 全局样式重置 */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }

    /* 练习页面主体样式 - 使用充满活力的渐变背景 */
    .practice-system {
      background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
      min-height: 100vh;
      padding: 20px;
      color: #333;
    }

    /* 容器样式 - 居中显示内容 */
    .container {
      max-width: 1000px;
      margin: 0 auto;
    }

    /* 导航栏样式 */
    .navbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: rgba(255, 255, 255, 0.95);
      padding: 15px 30px;
      border-radius: 12px;
      margin-bottom: 20px;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .nav-brand {
      font-size: 24px;
      font-weight: bold;
      color: #4CAF50;
      display: flex;
      align-items: center;
    }

    .nav-buttons {
      display: flex;
      gap: 15px;
    }

    .btn {
      padding: 10px 20px;
      border-radius: 8px;
      text-decoration: none;
      font-weight: 600;
      transition: all 0.3s;
      display: inline-flex;
      align-items: center;
    }

    .btn-outline {
      border: 2px solid #4CAF50;
      color: #4CAF50;
      background: transparent;
    }

    .btn-outline:hover {
      background: #4CAF50;
      color: white;
    }

    /* 练习卡片容器 - 主要内容区域 */
    .practice-card {
      background: white;
      border-radius: 15px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
      overflow: hidden;
      margin-bottom: 20px;
    }

    /* 卡片头部样式 */
    .card-header {
      padding: 25px 30px;
      background: linear-gradient(135deg, #f8f9fa, #e9ecef);
      border-bottom: 1px solid #dee2e6;
    }

    .card-title {
      font-size: 28px;
      color: #333;
      margin-bottom: 8px;
    }

    .card-subtitle {
      color: #666;
      font-size: 16px;
      line-height: 1.5;
    }

    /* 卡片主体内容区域 */
    .card-body {
      padding: 30px;
    }

    /* 练习模式选择区域 */
    .practice-modes {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }

    /* 练习模式卡片样式 */
    .mode-card {
      background: #f8f9fa;
      border-radius: 12px;
      padding: 25px;
      text-align: center;
      transition: all 0.3s;
      border: 2px solid transparent;
      cursor: pointer;
    }

    .mode-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    }

    .mode-card.selected {
      border-color: #4CAF50;
      background: #e8f5e8;
    }

    .mode-card.premium {
      position: relative;
      border-color: #ffc107;
      background: #fff9e6;
    }

    .premium-badge {
      position: absolute;
      top: -10px;
      right: -10px;
      background: #ffc107;
      color: #333;
      padding: 5px 10px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: bold;
    }

    .mode-icon {
      font-size: 48px;
      margin-bottom: 15px;
    }

    .mode-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #333;
    }

    .mode-desc {
      color: #666;
      margin-bottom: 15px;
      line-height: 1.5;
    }

    .mode-details {
      font-size: 14px;
      color: #888;
      line-height: 1.4;
    }

    /* 练习控制区域 */
    .practice-controls {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 10px;
    }

    .practice-info {
      display: flex;
      gap: 20px;
    }

    .info-item {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .info-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 5px;
    }

    .info-value {
      font-size: 24px;
      font-weight: bold;
      color: #4CAF50;
    }

    /* 控制按钮样式 */
    .control-btn {
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
    }

    .btn-start {
      background: #4CAF50;
      color: white;
    }

    .btn-premium {
      background: #ffc107;
      color: #333;
    }

    .control-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
    }

    /* 练习区域样式 */
    .practice-area {
      display: none;
      background: #f8f9fa;
      border-radius: 10px;
      padding: 25px;
      margin-bottom: 25px;
    }

    /* 问题区域样式 */
    .question-area {
      margin-bottom: 25px;
    }

    .question-title {
      font-size: 20px;
      color: #333;
      margin-bottom: 15px;
      line-height: 1.5;
    }

    /* 选项区域样式 */
    .options-area {
      display: grid;
      grid-template-columns: 1fr;
      gap: 12px;
    }

    .option {
      background: white;
      border: 2px solid #e0e0e0;
      border-radius: 8px;
      padding: 15px;
      cursor: pointer;
      transition: all 0.2s;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .option:hover {
      border-color: #4CAF50;
      background: #f1f8e9;
    }

    .option.selected {
      border-color: #4CAF50;
      background: #e8f5e8;
    }

    .option-letter {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background: #e0e0e0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      color: #666;
      flex-shrink: 0;
    }

    .option.selected .option-letter {
      background: #4CAF50;
      color: white;
    }

    .option-content {
      flex: 1;
    }

    /* 填空练习样式 */
    .fill-blank-container {
      margin-bottom: 20px;
    }

    .blank-sentence {
      font-size: 16px;
      line-height: 1.6;
      margin-bottom: 15px;
    }

    .blank-input {
      border: 1px solid #ddd;
      border-radius: 4px;
      padding: 8px 12px;
      margin: 0 5px;
      width: 120px;
      font-size: 14px;
    }

    .blank-input:focus {
      border-color: #2196F3;
      outline: none;
    }

    /* 简答题样式 */
    .short-answer-container {
      margin-bottom: 20px;
    }

    .answer-textarea {
      width: 100%;
      min-height: 120px;
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-size: 14px;
      line-height: 1.5;
      resize: vertical;
    }

    .answer-textarea:focus {
      border-color: #2196F3;
      outline: none;
    }

    /* 反馈区域样式 */
    .feedback-area {
      margin-top: 20px;
      padding: 15px;
      border-radius: 8px;
      display: none;
    }

    .feedback-area.correct {
      background: #e8f5e8;
      border-left: 4px solid #4CAF50;
    }

    .feedback-area.incorrect {
      background: #ffebee;
      border-left: 4px solid #f44336;
    }

    .feedback-title {
      font-weight: bold;
      margin-bottom: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .feedback-correct .feedback-title {
      color: #4CAF50;
    }

    .feedback-incorrect .feedback-title {
      color: #f44336;
    }

    .feedback-content {
      line-height: 1.5;
    }

    /* 练习进度区域 */
    .practice-progress {
      margin-bottom: 25px;
    }

    .progress-bar-container {
      width: 100%;
      height: 10px;
      background: #e0e0e0;
      border-radius: 5px;
      overflow: hidden;
      margin-bottom: 10px;
    }

    .progress-bar {
      height: 100%;
      background: #4CAF50;
      border-radius: 5px;
      transition: width 0.3s;
    }

    .progress-text {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #666;
    }

    /* 练习结果区域 */
    .practice-results {
      display: none;
      text-align: center;
      padding: 40px 20px;
    }

    .result-icon {
      font-size: 80px;
      margin-bottom: 20px;
    }

    .result-title {
      font-size: 32px;
      color: #333;
      margin-bottom: 10px;
    }

    .result-score {
      font-size: 48px;
      font-weight: bold;
      color: #4CAF50;
      margin-bottom: 20px;
    }

    .result-details {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      margin: 25px 0;
      max-width: 500px;
      margin-left: auto;
      margin-right: auto;
    }

    .result-detail {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 8px;
    }

    .detail-value {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
    }

    .detail-label {
      font-size: 14px;
      color: #666;
    }

    .result-actions {
      display: flex;
      gap: 15px;
      justify-content: center;
      margin-top: 30px;
    }

    .result-btn {
      padding: 12px 25px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-weight: 600;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-retry {
      background: #4CAF50;
      color: white;
    }

    .btn-next {
      background: #2196F3;
      color: white;
    }

    .btn-gym {
      background: #6c757d;
      color: white;
    }

    /* 计时器样式 - 营造紧迫感 */
    .timer-practice {
      position: fixed;
      top: 20px;
      right: 20px;
      background: rgba(255, 255, 255, 0.9);
      padding: 10px 15px;
      border-radius: 20px;
      font-size: 14px;
      color: #f44336;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      z-index: 100;
      font-weight: bold;
    }

    /* 错题练习提示 */
    .mistake-notice {
      background: #fff3cd;
      border: 1px solid #ffc107;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      display: none;
    }

    /* 间隔重复记忆状态显示 */
    .memory-status {
      background: #e3f2fd;
      border: 1px solid #2196F3;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      display: none;
    }

    .memory-level {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 10px;
    }

    .memory-bar {
      flex: 1;
      height: 8px;
      background: #e0e0e0;
      border-radius: 4px;
      overflow: hidden;
    }

    .memory-progress {
      height: 100%;
      background: #2196F3;
      border-radius: 4px;
      transition: width 0.3s;
    }

    .memory-info {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #666;
    }

    /* 付费功能提示 */
    .premium-notice {
      background: #fff3cd;
      border: 1px solid #ffc107;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      text-align: center;
    }

    .premium-features {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
      margin: 20px 0;
    }

    .premium-feature {
      background: #fff9e6;
      padding: 15px;
      border-radius: 8px;
      text-align: center;
    }

    /* 响应式设计 - 移动设备适配 */
    @media (max-width: 768px) {
      .navbar {
        flex-direction: column;
        gap: 15px;
      }

      .nav-buttons {
        flex-direction: column;
        width: 100%;
        gap: 10px;
      }

      .btn {
        width: 100%;
        justify-content: center;
      }

      .practice-modes {
        grid-template-columns: 1fr;
      }

      .practice-controls {
        flex-direction: column;
        gap: 15px;
      }

      .practice-info {
        width: 100%;
        justify-content: space-around;
      }

      .result-actions {
        flex-direction: column;
        align-items: center;
      }

      .result-btn {
        width: 100%;
        max-width: 250px;
        justify-content: center;
      }

      .timer-practice {
        position: relative;
        top: auto;
        right: auto;
        margin-bottom: 20px;
        display: inline-block;
      }

      .premium-features {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body class="practice-system">
<div class="container">
  <!-- 导航栏 -->
  <nav class="navbar">
    <div class="nav-brand">
      <span style="margin-right: 10px;">🔁</span> 渐进学习平台 - 练习系统
    </div>
    <div class="nav-buttons">
      <!-- 返回训练馆按钮 -->
      <a href="/knowledge-gym" class="btn btn-outline">返回训练馆</a>
      <!-- 返回首页按钮 -->
      <a href="/" class="btn btn-outline">返回首页</a>
    </div>
  </nav>

  <!-- 练习计时器 - 营造紧迫感 -->
  <div class="timer-practice" id="practiceTimer">
    ⏱️ 剩余时间: <span id="timeRemaining">10:00</span>
  </div>

  <!-- 练习卡片 - 主要内容容器 -->
  <div class="practice-card">
    <!-- 卡片头部 -->
    <div class="card-header">
      <h1 class="card-title" id="practiceTitle">Spring IoC容器 - 练习</h1>
      <p class="card-subtitle" id="practiceDescription">通过重复练习巩固记忆，建立肌肉记忆</p>
    </div>

    <!-- 卡片主体内容 -->
    <div class="card-body">
      <!-- 错题练习提示 -->
      <div class="mistake-notice" id="mistakeNotice">
        <h4>📝 错题强化练习</h4>
        <p>系统检测到您之前有 <span id="mistakeCount">0</span> 道错题，现在开始强化练习这些题目。</p>
      </div>

      <!-- 间隔重复记忆状态 -->
      <div class="memory-status" id="memoryStatus">
        <h4>📅 智能复习状态</h4>
        <div class="memory-level">
          <span>记忆强度:</span>
          <div class="memory-bar">
            <div class="memory-progress" id="memoryProgress" style="width: 0%"></div>
          </div>
          <span id="memoryLevelText">新学</span>
        </div>
        <div class="memory-info">
          <span>下次复习: <span id="nextReviewDate">-</span></span>
          <span>复习次数: <span id="reviewCount">0</span></span>
        </div>
      </div>

      <!-- 付费功能提示 -->
      <div class="premium-notice" id="premiumNotice" style="display: none;">
        <h4>🚀 升级到高级版解锁智能学习功能</h4>
        <p>智能复习功能基于间隔重复算法，能显著提高记忆效率</p>

        <div class="premium-features">
          <div class="premium-feature">
            <h5>📅 智能复习计划</h5>
            <p>基于记忆曲线自动安排最佳复习时间</p>
          </div>
          <div class="premium-feature">
            <h5>🧠 主动回忆训练</h5>
            <p>强制大脑提取知识，加深记忆痕迹</p>
          </div>
          <div class="premium-feature">
            <h5>📊 学习分析报告</h5>
            <p>详细的学习数据分析和个性化建议</p>
          </div>
        </div>

        <button class="control-btn btn-premium" onclick="upgradeToPremium()">
          💎 升级到高级版
        </button>
      </div>

      <!-- 练习模式选择区域 -->
      <div class="practice-modes" id="modeSelection">
        <!-- 基础重复模式 -->
        <div class="mode-card" data-mode="basic">
          <div class="mode-icon">🔄</div>
          <h3 class="mode-title">基础重复</h3>
          <p class="mode-desc">快速巩固核心概念，适合时间有限或已掌握基础的用户</p>
          <div class="mode-details">
            <p>• 5道核心题目</p>
            <p>• 5分钟限时</p>
            <p>• 即时反馈</p>
          </div>
        </div>

        <!-- 标准练习模式 -->
        <div class="mode-card selected" data-mode="standard">
          <div class="mode-icon">⚡</div>
          <h3 class="mode-title">标准练习</h3>
          <p class="mode-desc">平衡效率与效果，推荐大多数用户使用</p>
          <div class="mode-details">
            <p>• 10道全面题目</p>
            <p>• 10分钟限时</p>
            <p>• 详细解析</p>
          </div>
        </div>

        <!-- 深度掌握模式 -->
        <div class="mode-card" data-mode="deep">
          <div class="mode-icon">🏋️</div>
          <h3 class="mode-title">深度掌握</h3>
          <p class="mode-desc">彻底掌握知识点，适合需要牢固掌握的用户</p>
          <div class="mode-details">
            <p>• 15道深度题目</p>
            <p>• 15分钟限时</p>
            <p>• 进阶挑战</p>
          </div>
        </div>

        <!-- 智能复习模式（付费功能） -->
        <div class="mode-card premium" data-mode="smart" id="smartModeCard">
          <div class="premium-badge">高级功能</div>
          <div class="mode-icon">🧠</div>
          <h3 class="mode-title">智能复习</h3>
          <p class="mode-desc">基于间隔重复算法，在最佳时机复习，最大化记忆效率</p>
          <div class="mode-details">
            <p>• 个性化复习计划</p>
            <p>• 记忆曲线跟踪</p>
            <p>• 主动回忆训练</p>
          </div>
        </div>
      </div>

      <!-- 练习控制区域 -->
      <div class="practice-controls" id="practiceControls">
        <div class="practice-info">
          <div class="info-item">
            <span class="info-label">题目数量</span>
            <span class="info-value" id="questionCount">10</span>
          </div>
          <div class="info-item">
            <span class="info-label">限时</span>
            <span class="info-value" id="timeLimit">10:00</span>
          </div>
          <div class="info-item">
            <span class="info-label">目标分数</span>
            <span class="info-value" id="targetScore">80%</span>
          </div>
        </div>
        <button class="control-btn btn-start" onclick="startPractice()">
          🚀 开始练习
        </button>
      </div>

      <!-- 练习区域 -->
      <div class="practice-area" id="practiceArea">
        <!-- 练习进度 -->
        <div class="practice-progress">
          <div class="progress-bar-container">
            <div class="progress-bar" id="progressBar" style="width: 0%"></div>
          </div>
          <div class="progress-text">
            <span id="currentQuestion">题目 1/10</span>
            <span id="correctCount">正确: 0</span>
          </div>
        </div>

        <!-- 问题区域 -->
        <div class="question-area">
          <h3 class="question-title" id="questionText">什么是控制反转(IoC)的主要作用？</h3>
          <div class="options-area" id="optionsContainer">
            <!-- 选项将通过JavaScript动态生成 -->
          </div>
        </div>

        <!-- 检查答案按钮 -->
        <button class="control-btn btn-start" onclick="checkAnswer()" id="checkBtn" style="margin-top: 20px;">
          ✅ 检查答案
        </button>

        <!-- 反馈区域 -->
        <div class="feedback-area" id="feedbackArea">
          <!-- 反馈内容将通过JavaScript动态生成 -->
        </div>

        <!-- 下一题按钮 -->
        <button class="control-btn btn-start" onclick="nextQuestion()" id="nextBtn" style="display: none; margin-top: 20px;">
          ⏭️ 下一题
        </button>
      </div>

      <!-- 练习结果区域 -->
      <div class="practice-results" id="resultsArea">
        <!-- 结果内容将通过JavaScript动态生成 -->
      </div>
    </div>
  </div>
</div>

<script>
  // =============================================================================
  // 练习数据配置
  // =============================================================================

  /**
   * 练习内容配置对象
   * 包含当前知识点的所有练习题目和配置
   */
  const practiceContent = {
    // 当前知识点信息
    knowledgePoint: {
      id: 1,
      title: 'Spring IoC容器',
      description: '通过重复练习巩固记忆，建立肌肉记忆'
    },

    // 练习模式配置
    practiceModes: {
      basic: {
        name: '基础重复',
        questionCount: 5,
        timeLimit: 5 * 60, // 5分钟，单位秒
        targetScore: 60
      },
      standard: {
        name: '标准练习',
        questionCount: 10,
        timeLimit: 10 * 60, // 10分钟，单位秒
        targetScore: 80
      },
      deep: {
        name: '深度掌握',
        questionCount: 15,
        timeLimit: 15 * 60, // 15分钟，单位秒
        targetScore: 90
      },
      smart: {
        name: '智能复习',
        questionCount: 10, // 智能复习模式下题目数量动态决定
        timeLimit: 15 * 60, // 15分钟，单位秒
        targetScore: 80
      }
    },

    // 练习题目数组 - 包含多种题型
    questions: [
      {
        id: 1,
        type: "multiple_choice",
        question: '什么是控制反转(IoC)的主要作用？',
        options: [
          '将对象的创建和管理控制权从应用程序代码转移到容器',
          '提高代码的执行效率',
          '减少代码的编写量',
          '简化数据库操作'
        ],
        correctAnswer: 0,
        explanation: '控制反转的核心思想是将对象的创建和管理权从应用程序代码转移到容器，实现解耦。',
        difficulty: "easy"
      },
      {
        id: 2,
        type: "fill_blank",
        question: '请填写依赖注入的三种主要方式：',
        sentence: '依赖注入的三种主要方式是：<input class="blank-input" id="blank1">、<input class="blank-input" id="blank2">和<input class="blank-input" id="blank3">。',
        answers: ["构造函数注入", "Setter方法注入", "字段注入"],
        explanation: '依赖注入的三种主要方式是构造函数注入、Setter方法注入和字段注入，Spring都支持这些方式。',
        difficulty: "easy"
      },
      {
        id: 3,
        type: "multiple_choice",
        question: 'Spring Bean的默认作用域是什么？',
        options: [
          'singleton（单例）',
          'prototype（原型）',
          'request（请求）',
          'session（会话）'
        ],
        correctAnswer: 0,
        explanation: 'Spring Bean的默认作用域是singleton，每个Spring容器中只有一个实例。',
        difficulty: "medium"
      },
      {
        id: 4,
        type: "short_answer",
        question: '请简要描述Spring Bean的singleton和prototype作用域的区别：',
        answerKeywords: ["singleton", "prototype", "单例", "原型", "一个实例", "多个实例"],
        modelAnswer: 'singleton作用域的Bean在Spring容器中只有一个实例，而prototype作用域的Bean每次请求都会创建新的实例。',
        explanation: 'singleton是默认作用域，每个容器只有一个实例；prototype每次请求都创建新实例。',
        difficulty: "medium"
      },
      {
        id: 5,
        type: "multiple_choice",
        question: '以下哪种配置方式在现代Spring开发中最推荐？',
        options: [
          '注解配置，结合Java配置',
          '纯XML配置',
          '纯Java配置',
          '属性文件配置'
        ],
        correctAnswer: 0,
        explanation: '现代Spring开发中最推荐注解配置结合Java配置，代码更简洁直观。',
        difficulty: "medium"
      },
      {
        id: 6,
        type: "multiple_choice",
        question: 'Spring容器的主要职责是什么？',
        options: [
          '创建、配置和管理Bean的整个生命周期，包括依赖注入',
          '处理HTTP请求和响应',
          '管理数据库连接',
          '提供安全认证和授权'
        ],
        correctAnswer: 0,
        explanation: 'Spring容器是Spring框架的核心，负责创建、配置和管理Bean的整个生命周期。',
        difficulty: "medium"
      },
      {
        id: 7,
        type: "fill_blank",
        question: '请填写Spring Bean的常见作用域：',
        sentence: 'Spring Bean的常见作用域包括：<input class="blank-input" id="blank1">（默认）、<input class="blank-input" id="blank2">、<input class="blank-input" id="blank3">、<input class="blank-input" id="blank4">和<input class="blank-input" id="blank5">。',
        answers: ["singleton", "prototype", "request", "session", "application"],
        explanation: 'Spring Bean的常见作用域：singleton（默认）、prototype、request、session、application。',
        difficulty: "medium"
      },
      {
        id: 8,
        type: "multiple_choice",
        question: '@Autowired注解的作用是什么？',
        options: [
          '自动注入依赖的Bean',
          '标记一个类为Spring组件',
          '定义Bean的作用域',
          '配置AOP切面'
        ],
        correctAnswer: 0,
        explanation: '@Autowired注解用于自动注入依赖的Bean，Spring容器会自动查找匹配的Bean并注入。',
        difficulty: "easy"
      },
      {
        id: 9,
        type: "short_answer",
        question: '请简要说明控制反转(IoC)带来的两个主要优势：',
        answerKeywords: ["解耦", "测试", "维护", "灵活", "复用"],
        modelAnswer: '控制反转的主要优势：1) 降低组件之间的耦合度，提高代码可维护性；2) 便于单元测试，可以轻松替换依赖的实现。',
        explanation: 'IoC通过依赖注入降低了组件间的耦合，使代码更易于测试和维护。',
        difficulty: "hard"
      },
      {
        id: 10,
        type: "multiple_choice",
        question: '以下关于Bean作用域的说法哪个是正确的？',
        options: [
          'prototype作用域的Bean每次请求都会创建新实例',
          'singleton作用域的Bean每个HTTP请求创建一个实例',
          'request作用域的Bean在整个应用中只有一个实例',
          'session作用域的Bean每次请求都会创建新实例'
        ],
        correctAnswer: 0,
        explanation: 'prototype作用域的Bean每次请求都会创建新实例，而singleton作用域的Bean每个容器只有一个实例。',
        difficulty: "medium"
      }
    ],

    // 当前练习状态
    currentMode: 'standard',
    currentQuestionIndex: 0,
    selectedOption: null,
    correctAnswers: 0,
    startTime: null,
    timerInterval: null,
    timeRemaining: 0,
    practiceActive: false,

    // 错题管理
    mistakeQuestions: [], // 存储错题ID
    isMistakePractice: false, // 是否为错题练习模式
    mistakePracticeIndex: 0, // 错题练习索引

    // 间隔重复系统配置
    spacedRepetition: {
      // 记忆级别配置 - 基于SM-2算法
      levels: [
        { interval: 1, name: '新学', color: '#ff6b6b' },           // 1天后复习
        { interval: 3, name: '熟悉', color: '#4ecdc4' },           // 3天后复习
        { interval: 7, name: '掌握', color: '#45b7d1' },           // 7天后复习
        { interval: 14, name: '熟练', color: '#96ceb4' },          // 14天后复习
        { interval: 30, name: '精通', color: '#feca57' },          // 30天后复习
        { interval: 90, name: '永久', color: '#ff9ff3' }           // 90天后复习
      ],
      // 用户记忆状态存储
      userMemory: {} // questionId -> { level, nextReview, lastReviewed, easeFactor, reviewCount }
    },

    // 用户订阅状态
    userSubscription: {
      isPremium: false, // 默认不是高级用户
      expiryDate: null  // 订阅过期日期
    }
  };

  // =============================================================================
  // 间隔重复系统核心功能
  // =============================================================================

  /**
   * 间隔重复引擎 - 基于SM-2算法
   */
  class SpacedRepetitionEngine {
    /**
     * 初始化间隔重复系统
     */
    static init() {
      // 从本地存储加载用户记忆状态
      const savedMemory = localStorage.getItem('spacedRepetitionMemory');
      if (savedMemory) {
        practiceContent.spacedRepetition.userMemory = JSON.parse(savedMemory);
      }

      // 从本地存储加载用户订阅状态
      const savedSubscription = localStorage.getItem('userSubscription');
      if (savedSubscription) {
        practiceContent.userSubscription = JSON.parse(savedSubscription);
      }

      console.log('间隔重复系统初始化完成');
    }

    /**
     * 保存记忆状态到本地存储
     */
    static saveMemoryState() {
      localStorage.setItem('spacedRepetitionMemory',
              JSON.stringify(practiceContent.spacedRepetition.userMemory));
    }

    /**
     * 根据回答质量更新记忆状态
     * @param {number} questionId - 题目ID
     * @param {number} performance - 表现评分 (0-5)
     * @returns {Object} 更新后的记忆状态
     */
    static updateMemoryState(questionId, performance) {
      // 获取当前记忆状态，如果不存在则初始化
      let memory = practiceContent.spacedRepetition.userMemory[questionId] || {
        level: 0,           // 记忆级别 (0-5)
        nextReview: Date.now(), // 下次复习时间
        lastReviewed: Date.now(), // 最后复习时间
        easeFactor: 2.5,    // 难度因子 (1.3-2.5)
        reviewCount: 0      // 复习次数
      };

      // 更新复习次数
      memory.reviewCount++;
      memory.lastReviewed = Date.now();

      // 基于SM-2算法更新记忆状态
      if (performance >= 4) { // 回答正确且容易
        if (memory.level === 0) {
          memory.level = 1;
          memory.nextReview = Date.now() + practiceContent.spacedRepetition.levels[1].interval * 24 * 60 * 60 * 1000;
        } else {
          memory.level = Math.min(memory.level + 1, 5);
          const interval = practiceContent.spacedRepetition.levels[memory.level].interval * memory.easeFactor;
          memory.nextReview = Date.now() + interval * 24 * 60 * 60 * 1000;
        }
        memory.easeFactor = Math.min(2.5, memory.easeFactor + 0.1);
      } else if (performance >= 3) { // 回答正确但困难
        // 保持当前级别，但重置间隔
        memory.nextReview = Date.now() + practiceContent.spacedRepetition.levels[memory.level].interval * 24 * 60 * 60 * 1000;
      } else { // 回答错误
        memory.level = Math.max(0, memory.level - 1);
        memory.easeFactor = Math.max(1.3, memory.easeFactor - 0.2);
        memory.nextReview = Date.now() + practiceContent.spacedRepetition.levels[0].interval * 24 * 60 * 60 * 1000;
      }

      // 保存更新后的记忆状态
      practiceContent.spacedRepetition.userMemory[questionId] = memory;
      this.saveMemoryState();

      console.log(`题目 ${questionId} 记忆状态更新: 级别=${memory.level}, 下次复习=${new Date(memory.nextReview).toLocaleDateString()}`);
      return memory;
    }

    /**
     * 获取需要复习的题目ID列表
     * @returns {Array} 需要复习的题目ID数组
     */
    static getDueReviews() {
      const now = Date.now();
      const dueQuestions = [];

      // 遍历所有题目的记忆状态
      for (const [questionId, memory] of Object.entries(practiceContent.spacedRepetition.userMemory)) {
        // 如果当前时间超过了下次复习时间，则加入复习列表
        if (memory.nextReview <= now) {
          dueQuestions.push(parseInt(questionId));
        }
      }

      // 如果没有需要复习的题目，返回新题目
      if (dueQuestions.length === 0) {
        return this.getNewQuestions(5); // 返回5道新题目
      }

      console.log(`找到 ${dueQuestions.length} 道需要复习的题目`);
      return dueQuestions;
    }

    /**
     * 获取新题目（尚未学习过的题目）
     * @param {number} count - 需要的新题目数量
     * @returns {Array} 新题目ID数组
     */
    static getNewQuestions(count) {
      const newQuestions = [];

      // 遍历所有题目
      for (const question of practiceContent.questions) {
        // 如果该题目还没有记忆状态，则认为是新题目
        if (!practiceContent.spacedRepetition.userMemory[question.id]) {
          newQuestions.push(question.id);
          if (newQuestions.length >= count) {
            break;
          }
        }
      }

      console.log(`找到 ${newQuestions.length} 道新题目`);
      return newQuestions;
    }

    /**
     * 获取题目的记忆状态显示信息
     * @param {number} questionId - 题目ID
     * @returns {Object} 记忆状态显示信息
     */
    static getMemoryStatus(questionId) {
      const memory = practiceContent.spacedRepetition.userMemory[questionId];
      if (!memory) {
        return {
          level: 0,
          levelText: '新学',
          progress: 0,
          nextReview: '立即学习',
          reviewCount: 0
        };
      }

      const levelConfig = practiceContent.spacedRepetition.levels[memory.level];
      const progress = (memory.level / 5) * 100; // 计算进度百分比

      // 计算下次复习日期
      const nextReviewDate = new Date(memory.nextReview);
      const now = new Date();
      const daysDiff = Math.ceil((nextReviewDate - now) / (1000 * 60 * 60 * 24));

      let nextReviewText;
      if (daysDiff <= 0) {
        nextReviewText = '立即复习';
      } else if (daysDiff === 1) {
        nextReviewText = '明天';
      } else {
        nextReviewText = `${daysDiff}天后`;
      }

      return {
        level: memory.level,
        levelText: levelConfig.name,
        progress: progress,
        nextReview: nextReviewText,
        reviewCount: memory.reviewCount
      };
    }

    /**
     * 检查用户是否有权限使用智能复习功能
     * @returns {boolean} 是否有权限
     */
    static hasPremiumAccess() {
      // 检查用户订阅状态
      if (!practiceContent.userSubscription.isPremium) {
        return false;
      }

      // 检查订阅是否过期
      if (practiceContent.userSubscription.expiryDate &&
              new Date(practiceContent.userSubscription.expiryDate) < new Date()) {
        practiceContent.userSubscription.isPremium = false;
        this.saveSubscriptionState();
        return false;
      }

      return true;
    }

    /**
     * 保存用户订阅状态
     */
    static saveSubscriptionState() {
      localStorage.setItem('userSubscription',
              JSON.stringify(practiceContent.userSubscription));
    }
  }

  // =============================================================================
  // 页面初始化函数
  // =============================================================================

  /**
   * 页面加载完成后初始化练习页面
   */
  document.addEventListener('DOMContentLoaded', function() {
    // 1. 初始化间隔重复系统
    SpacedRepetitionEngine.init();

    // 2. 更新页面标题和描述
    updateContentDisplay();

    // 3. 初始化模式选择
    initializeModeSelection();

    // 4. 更新模式信息显示
    updateModeInfo();

    // 5. 检查是否有错题需要练习
    checkMistakeQuestions();

    // 6. 检查用户订阅状态并更新界面
    updatePremiumUI();

    console.log('练习页面初始化完成');
  });

  // =============================================================================
  // 核心功能函数
  // =============================================================================

  /**
   * 更新页面内容显示
   */
  function updateContentDisplay() {
    document.getElementById('practiceTitle').textContent =
            practiceContent.knowledgePoint.title + ' - 练习';
    document.getElementById('practiceDescription').textContent =
            practiceContent.knowledgePoint.description;
  }

  /**
   * 初始化模式选择
   * 设置模式选择卡的点击事件
   */
  function initializeModeSelection() {
    const modeCards = document.querySelectorAll('.mode-card');

    modeCards.forEach(card => {
      card.addEventListener('click', function() {
        // 检查是否为付费模式
        if (this.dataset.mode === 'smart' && !SpacedRepetitionEngine.hasPremiumAccess()) {
          showPremiumNotice();
          return;
        }

        // 移除所有卡的选中状态
        modeCards.forEach(c => c.classList.remove('selected'));

        // 添加当前卡的选中状态
        this.classList.add('selected');

        // 更新当前模式
        practiceContent.currentMode = this.dataset.mode;

        // 更新模式信息显示
        updateModeInfo();

        console.log('已选择模式:', practiceContent.currentMode);
      });
    });
  }

  /**
   * 更新模式信息显示
   * 根据选择的模式更新题目数量、限时和目标分数
   */
  function updateModeInfo() {
    const mode = practiceContent.practiceModes[practiceContent.currentMode];

    // 对于智能复习模式，题目数量是动态的
    let questionCount = mode.questionCount;
    if (practiceContent.currentMode === 'smart') {
      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      questionCount = Math.min(mode.questionCount, dueReviews.length);
    }

    document.getElementById('questionCount').textContent = questionCount;
    document.getElementById('timeLimit').textContent = formatTime(mode.timeLimit);
    document.getElementById('targetScore').textContent = mode.targetScore + '%';
  }

  /**
   * 检查是否有错题需要练习
   * 从本地存储中获取错题记录
   */
  function checkMistakeQuestions() {
    // 从本地存储获取错题记录
    const mistakeData = localStorage.getItem('mistakeQuestions');
    if (mistakeData) {
      practiceContent.mistakeQuestions = JSON.parse(mistakeData);

      // 如果有错题，显示错题练习提示
      if (practiceContent.mistakeQuestions.length > 0) {
        document.getElementById('mistakeNotice').style.display = 'block';
        document.getElementById('mistakeCount').textContent = practiceContent.mistakeQuestions.length;
      }
    }
  }

  /**
   * 显示付费功能提示
   */
  function showPremiumNotice() {
    document.getElementById('premiumNotice').style.display = 'block';

    // 滚动到提示区域
    document.getElementById('premiumNotice').scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    });
  }

  /**
   * 升级到高级版
   */
  function upgradeToPremium() {
    // 在实际项目中，这里会跳转到支付页面或处理订阅逻辑
    // 这里我们模拟订阅成功

    practiceContent.userSubscription.isPremium = true;
    practiceContent.userSubscription.expiryDate = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(); // 1年后过期

    SpacedRepetitionEngine.saveSubscriptionState();
    updatePremiumUI();

    alert('🎉 恭喜您已成功升级到高级版！现在可以享受智能复习功能了。');

    // 自动选择智能复习模式
    document.querySelector('.mode-card[data-mode="smart"]').click();
  }

  /**
   * 更新付费相关UI
   */
  function updatePremiumUI() {
    const isPremium = SpacedRepetitionEngine.hasPremiumAccess();
    const smartModeCard = document.getElementById('smartModeCard');

    if (isPremium) {
      // 用户是高级用户，移除付费提示
      smartModeCard.classList.remove('premium');
      const badge = smartModeCard.querySelector('.premium-badge');
      if (badge) {
        badge.remove();
      }
      document.getElementById('premiumNotice').style.display = 'none';
    } else {
      // 用户不是高级用户，显示付费提示
      smartModeCard.classList.add('premium');
    }
  }

  /**
   * 开始练习
   * 初始化练习状态并显示第一道题目
   */
  function startPractice() {
    // 检查是否进入错题练习模式
    const startMistakePractice = practiceContent.mistakeQuestions.length > 0 &&
            confirm(`检测到您有 ${practiceContent.mistakeQuestions.length} 道错题，是否先练习错题？`);

    if (startMistakePractice) {
      // 进入错题练习模式
      practiceContent.isMistakePractice = true;
      practiceContent.mistakePracticeIndex = 0;

      // 设置错题练习的题目数量
      const mode = practiceContent.practiceModes[practiceContent.currentMode];
      mode.questionCount = practiceContent.mistakeQuestions.length;

      // 更新显示
      document.getElementById('questionCount').textContent = mode.questionCount;
      document.getElementById('mistakeNotice').style.display = 'none';
    }

    // 1. 隐藏模式选择和控制区域
    document.getElementById('modeSelection').style.display = 'none';
    document.getElementById('practiceControls').style.display = 'none';

    // 2. 显示练习区域
    document.getElementById('practiceArea').style.display = 'block';

    // 3. 重置练习状态
    resetPracticeState();

    // 4. 加载第一道题目
    loadCurrentQuestion();

    // 5. 开始计时器
    startPracticeTimer();

    console.log('练习开始，模式:', practiceContent.currentMode);
    if (practiceContent.isMistakePractice) {
      console.log('进入错题练习模式，错题数量:', practiceContent.mistakeQuestions.length);
    }
  }

  /**
   * 重置练习状态
   * 将练习状态重置为初始值
   */
  function resetPracticeState() {
    const mode = practiceContent.practiceModes[practiceContent.currentMode];

    practiceContent.currentQuestionIndex = 0;
    practiceContent.selectedOption = null;
    practiceContent.correctAnswers = 0;
    practiceContent.timeRemaining = mode.timeLimit;
    practiceContent.practiceActive = true;

    // 重置进度条
    document.getElementById('progressBar').style.width = '0%';

    // 更新进度文本
    updateProgressText();

    // 隐藏下一题按钮
    document.getElementById('nextBtn').style.display = 'none';

    // 显示检查答案按钮
    document.getElementById('checkBtn').style.display = 'block';
    document.getElementById('checkBtn').disabled = true;

    // 隐藏反馈区域
    document.getElementById('feedbackArea').style.display = 'none';

    // 隐藏记忆状态显示（会在加载题目时根据需要显示）
    document.getElementById('memoryStatus').style.display = 'none';
  }

  /**
   * 更新进度文本
   */
  function updateProgressText() {
    const mode = practiceContent.practiceModes[practiceContent.currentMode];
    let total, current;

    if (practiceContent.isMistakePractice) {
      // 错题练习模式
      total = practiceContent.mistakeQuestions.length;
      current = practiceContent.mistakePracticeIndex + 1;
    } else if (practiceContent.currentMode === 'smart') {
      // 智能复习模式
      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      total = Math.min(mode.questionCount, dueReviews.length);
      current = practiceContent.currentQuestionIndex + 1;
    } else {
      // 正常练习模式
      total = mode.questionCount;
      current = practiceContent.currentQuestionIndex + 1;
    }

    document.getElementById('currentQuestion').textContent = `题目 ${current}/${total}`;
    document.getElementById('correctCount').textContent = '正确: ' + practiceContent.correctAnswers;

    // 更新进度条
    const progress = ((current - 1) / total) * 100;
    document.getElementById('progressBar').style.width = `${progress}%`;
  }

  /**
   * 加载当前题目
   * 根据currentQuestionIndex显示对应的题目和选项
   */
  function loadCurrentQuestion() {
    let question;
    let questionId;

    if (practiceContent.isMistakePractice) {
      // 错题练习模式：从错题列表中获取题目
      questionId = practiceContent.mistakeQuestions[practiceContent.mistakePracticeIndex];
      question = practiceContent.questions.find(q => q.id === questionId);
    } else if (practiceContent.currentMode === 'smart') {
      // 智能复习模式：从需要复习的题目中获取
      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      questionId = dueReviews[practiceContent.currentQuestionIndex];
      question = practiceContent.questions.find(q => q.id === questionId);
    } else {
      // 正常练习模式：从题目列表中按顺序获取
      question = practiceContent.questions[practiceContent.currentQuestionIndex];
      questionId = question.id;
    }

    // 更新问题文本
    document.getElementById('questionText').textContent = question.question;

    // 根据题型生成不同的内容
    const optionsContainer = document.getElementById('optionsContainer');
    optionsContainer.innerHTML = '';

    switch (question.type) {
      case 'multiple_choice':
        generateMultipleChoice(question, optionsContainer);
        break;
      case 'fill_blank':
        generateFillBlank(question, optionsContainer);
        break;
      case 'short_answer':
        generateShortAnswer(question, optionsContainer);
        break;
    }

    // 如果是智能复习模式，显示记忆状态
    if (practiceContent.currentMode === 'smart') {
      showMemoryStatus(questionId);
    }

    // 更新进度文本
    updateProgressText();

    // 重置选择状态
    practiceContent.selectedOption = null;

    // 重置检查按钮状态
    document.getElementById('checkBtn').disabled = true;

    console.log(`已加载题目: ${practiceContent.isMistakePractice ? practiceContent.mistakePracticeIndex + 1 : practiceContent.currentQuestionIndex + 1}`);
  }

  /**
   * 显示题目的记忆状态
   * @param {number} questionId - 题目ID
   */
  function showMemoryStatus(questionId) {
    const memoryStatus = SpacedRepetitionEngine.getMemoryStatus(questionId);

    document.getElementById('memoryProgress').style.width = `${memoryStatus.progress}%`;
    document.getElementById('memoryLevelText').textContent = memoryStatus.levelText;
    document.getElementById('nextReviewDate').textContent = memoryStatus.nextReview;
    document.getElementById('reviewCount').textContent = memoryStatus.reviewCount;

    document.getElementById('memoryStatus').style.display = 'block';
  }

  /**
   * 生成选择题
   * @param {Object} question - 题目对象
   * @param {HTMLElement} container - 容器元素
   */
  function generateMultipleChoice(question, container) {
    question.options.forEach((option, index) => {
      const optionElement = document.createElement('div');
      optionElement.className = 'option';
      optionElement.dataset.optionIndex = index;

      optionElement.innerHTML = `
                <div class="option-letter">${String.fromCharCode(65 + index)}</div>
                <div class="option-content">${option}</div>
            `;

      // 添加选项点击事件
      optionElement.addEventListener('click', function() {
        selectOption(index);
      });

      container.appendChild(optionElement);
    });
  }

  /**
   * 生成填空题
   * @param {Object} question - 题目对象
   * @param {HTMLElement} container - 容器元素
   */
  function generateFillBlank(question, container) {
    const fillBlankContainer = document.createElement('div');
    fillBlankContainer.className = 'fill-blank-container';
    fillBlankContainer.innerHTML = `
            <div class="blank-sentence">${question.sentence}</div>
        `;
    container.appendChild(fillBlankContainer);

    // 为所有输入框添加事件监听器
    setTimeout(() => {
      const inputs = document.querySelectorAll('.blank-input');
      inputs.forEach(input => {
        input.addEventListener('input', enableCheckButton);
      });
    }, 0);
  }

  /**
   * 生成简答题
   * @param {Object} question - 题目对象
   * @param {HTMLElement} container - 容器元素
   */
  function generateShortAnswer(question, container) {
    const shortAnswerContainer = document.createElement('div');
    shortAnswerContainer.className = 'short-answer-container';
    shortAnswerContainer.innerHTML = `
            <textarea class="answer-textarea" id="shortAnswer" placeholder="请在此输入你的答案..." oninput="enableCheckButton()"></textarea>
        `;
    container.appendChild(shortAnswerContainer);
  }

  /**
   * 选择选项（选择题）
   * @param {number} optionIndex - 选项索引
   */
  function selectOption(optionIndex) {
    // 如果已经选择了选项，则忽略
    if (practiceContent.selectedOption !== null || !practiceContent.practiceActive) {
      return;
    }

    // 设置选中的选项
    practiceContent.selectedOption = optionIndex;

    // 更新选项样式
    const options = document.querySelectorAll('.option');
    options.forEach(option => {
      option.classList.remove('selected');
    });

    options[optionIndex].classList.add('selected');

    // 启用检查按钮
    document.getElementById('checkBtn').disabled = false;
  }

  /**
   * 启用检查按钮
   */
  function enableCheckButton() {
    document.getElementById('checkBtn').disabled = false;
  }

  /**
   * 检查答案
   * 显示答案反馈并更新得分
   */
  function checkAnswer() {
    let question;
    let questionId;

    if (practiceContent.isMistakePractice) {
      // 错题练习模式：从错题列表中获取题目
      questionId = practiceContent.mistakeQuestions[practiceContent.mistakePracticeIndex];
      question = practiceContent.questions.find(q => q.id === questionId);
    } else if (practiceContent.currentMode === 'smart') {
      // 智能复习模式：从需要复习的题目中获取
      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      questionId = dueReviews[practiceContent.currentQuestionIndex];
      question = practiceContent.questions.find(q => q.id === questionId);
    } else {
      // 正常练习模式：从题目列表中按顺序获取
      question = practiceContent.questions[practiceContent.currentQuestionIndex];
      questionId = question.id;
    }

    const feedbackArea = document.getElementById('feedbackArea');
    let isCorrect = false;

    // 根据题型检查答案
    switch (question.type) {
      case 'multiple_choice':
        isCorrect = checkMultipleChoiceAnswer(question);
        break;
      case 'fill_blank':
        isCorrect = checkFillBlankAnswer(question);
        break;
      case 'short_answer':
        isCorrect = checkShortAnswer(question);
        break;
    }

    // 更新统计
    if (practiceContent.isMistakePractice) {
      // 错题练习模式：只更新正确计数，不增加completed
      if (isCorrect) {
        practiceContent.correctAnswers++;
      }
    } else {
      // 正常练习模式：更新completed和correct
      if (isCorrect) {
        practiceContent.correctAnswers++;
      } else {
        // 记录错题
        recordMistake(question.id);
      }
    }

    // 如果是智能复习模式，更新记忆状态
    if (practiceContent.currentMode === 'smart') {
      // 根据回答质量计算表现评分 (0-5)
      let performance;
      if (isCorrect) {
        // 根据回答的自信程度或难度评分
        performance = 4; // 默认回答正确且容易
      } else {
        performance = 2; // 回答错误
      }

      SpacedRepetitionEngine.updateMemoryState(questionId, performance);
    }

    // 显示反馈
    if (isCorrect) {
      feedbackArea.className = 'feedback-area correct';
      feedbackArea.innerHTML = `
                <div class="feedback-title">
                    <span>✅ 正确！</span>
                </div>
                <div class="feedback-content">
                    <p>很好！你掌握了这个知识点。</p>
                    ${practiceContent.currentMode === 'smart' ? '<p>系统已记录您的学习进度，将在最佳时间提醒您复习。</p>' : ''}
                </div>
            `;
    } else {
      feedbackArea.className = 'feedback-area incorrect';
      feedbackArea.innerHTML = `
                <div class="feedback-title">
                    <span>❌ 不正确</span>
                </div>
                <div class="feedback-content">
                    <p><strong>解析：</strong> ${question.explanation}</p>
                    ${question.modelAnswer ? `<p><strong>参考答案：</strong> ${question.modelAnswer}</p>` : ''}
                    ${practiceContent.currentMode === 'smart' ? '<p>别担心，系统会调整复习计划，帮助您更好地掌握这个知识点。</p>' : ''}
                </div>
            `;
    }

    feedbackArea.style.display = 'block';
    document.getElementById('checkBtn').style.display = 'none';
    document.getElementById('nextBtn').style.display = 'block';

    // 更新进度文本
    updateProgressText();

    console.log(`答案${isCorrect ? '正确' : '错误'}，当前正确数: ${practiceContent.correctAnswers}`);
  }

  /**
   * 检查选择题答案
   * @param {Object} question - 题目对象
   * @returns {boolean} 是否正确
   */
  function checkMultipleChoiceAnswer(question) {
    return practiceContent.selectedOption === question.correctAnswer;
  }

  /**
   * 检查填空题答案
   * @param {Object} question - 题目对象
   * @returns {boolean} 是否正确
   */
  function checkFillBlankAnswer(question) {
    let allCorrect = true;
    for (let i = 0; i < question.answers.length; i++) {
      const input = document.getElementById(`blank${i+1}`);
      if (!input || input.value.trim().toLowerCase() !== question.answers[i].toLowerCase()) {
        allCorrect = false;
        break;
      }
    }
    return allCorrect;
  }

  /**
   * 检查简答题答案
   * @param {Object} question - 题目对象
   * @returns {boolean} 是否正确
   */
  function checkShortAnswer(question) {
    const userAnswer = document.getElementById('shortAnswer').value.toLowerCase();
    // 检查是否包含关键词
    return question.answerKeywords.some(keyword =>
            userAnswer.includes(keyword.toLowerCase())
    );
  }

  /**
   * 记录错题
   * @param {number} questionId - 题目ID
   */
  function recordMistake(questionId) {
    // 如果错题列表中还没有这个题目，则添加
    if (!practiceContent.mistakeQuestions.includes(questionId)) {
      practiceContent.mistakeQuestions.push(questionId);

      // 保存到本地存储
      localStorage.setItem('mistakeQuestions', JSON.stringify(practiceContent.mistakeQuestions));

      console.log(`记录错题: ${questionId}`);
    }
  }

  /**
   * 下一题
   * 加载下一道题目或结束练习
   */
  function nextQuestion() {
    if (practiceContent.isMistakePractice) {
      // 错题练习模式
      practiceContent.mistakePracticeIndex++;

      if (practiceContent.mistakePracticeIndex < practiceContent.mistakeQuestions.length) {
        loadCurrentQuestion();
      } else {
        // 错题练习完成
        endMistakePractice();
      }
    } else if (practiceContent.currentMode === 'smart') {
      // 智能复习模式
      practiceContent.currentQuestionIndex++;

      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      const mode = practiceContent.practiceModes[practiceContent.currentMode];
      const total = Math.min(mode.questionCount, dueReviews.length);

      if (practiceContent.currentQuestionIndex < total) {
        loadCurrentQuestion();
      } else {
        // 练习结束
        endPractice();
      }
    } else {
      // 正常练习模式
      practiceContent.currentQuestionIndex++;

      const mode = practiceContent.practiceModes[practiceContent.currentMode];
      if (practiceContent.currentQuestionIndex < mode.questionCount) {
        loadCurrentQuestion();
      } else {
        // 练习结束
        endPractice();
      }
    }

    // 隐藏反馈区域和下一题按钮
    document.getElementById('feedbackArea').style.display = 'none';
    document.getElementById('nextBtn').style.display = 'none';

    // 显示检查按钮
    document.getElementById('checkBtn').style.display = 'block';
    document.getElementById('checkBtn').disabled = true;
  }

  // =============================================================================
  // 计时器功能
  // =============================================================================

  /**
   * 开始练习计时器
   * 创建一个倒计时，时间到后自动结束练习
   */
  function startPracticeTimer() {
    // 更新计时器显示
    updateTimerDisplay();

    // 设置计时器，每秒更新一次
    practiceContent.timerInterval = setInterval(() => {
      practiceContent.timeRemaining--;
      updateTimerDisplay();

      // 时间到处理
      if (practiceContent.timeRemaining <= 0) {
        clearInterval(practiceContent.timerInterval);
        if (practiceContent.isMistakePractice) {
          endMistakePractice();
        } else {
          endPractice();
        }
      }
    }, 1000);
  }

  /**
   * 更新计时器显示
   */
  function updateTimerDisplay() {
    const minutes = Math.floor(practiceContent.timeRemaining / 60);
    const seconds = practiceContent.timeRemaining % 60;
    document.getElementById('timeRemaining').textContent =
            `${minutes}:${seconds.toString().padStart(2, '0')}`;

    // 时间不足1分钟时改变颜色
    if (practiceContent.timeRemaining < 60) {
      document.getElementById('practiceTimer').style.color = '#f44336';
    }
  }

  /**
   * 格式化时间
   * @param {number} seconds - 秒数
   * @returns {string} 格式化的时间字符串
   */
  function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    return `${minutes}:00`;
  }

  // =============================================================================
  // 练习结束功能
  // =============================================================================

  /**
   * 结束练习
   * 计算得分并显示结果
   */
  function endPractice() {
    // 停止计时器
    clearInterval(practiceContent.timerInterval);
    practiceContent.practiceActive = false;

    // 计算得分
    const mode = practiceContent.practiceModes[practiceContent.currentMode];
    let totalQuestions;

    if (practiceContent.currentMode === 'smart') {
      const dueReviews = SpacedRepetitionEngine.getDueReviews();
      totalQuestions = Math.min(mode.questionCount, dueReviews.length);
    } else {
      totalQuestions = mode.questionCount;
    }

    const score = Math.round((practiceContent.correctAnswers / totalQuestions) * 100);
    const passed = score >= mode.targetScore;

    // 隐藏练习区域
    document.getElementById('practiceArea').style.display = 'none';

    // 显示结果区域
    document.getElementById('resultsArea').style.display = 'block';

    // 生成结果HTML
    document.getElementById('resultsArea').innerHTML = createResultsHTML(score, passed, mode, totalQuestions);

    console.log(`练习结束，得分: ${score}%，${passed ? '通过' : '未通过'}`);
  }

  /**
   * 结束错题练习
   * 显示错题练习结果
   */
  function endMistakePractice() {
    // 停止计时器
    clearInterval(practiceContent.timerInterval);
    practiceContent.practiceActive = false;

    // 计算得分
    const score = Math.round((practiceContent.correctAnswers / practiceContent.mistakeQuestions.length) * 100);

    // 隐藏练习区域
    document.getElementById('practiceArea').style.display = 'none';

    // 显示结果区域
    document.getElementById('resultsArea').style.display = 'block';

    // 生成结果HTML
    document.getElementById('resultsArea').innerHTML = createMistakeResultsHTML(score);

    console.log(`错题练习结束，得分: ${score}%`);
  }

  /**
   * 创建结果HTML
   * @param {number} score - 得分
   * @param {boolean} passed - 是否通过
   * @param {object} mode - 练习模式配置
   * @param {number} totalQuestions - 总题目数
   * @returns {string} 结果HTML字符串
   */
  function createResultsHTML(score, passed, mode, totalQuestions) {
    // 智能复习模式特殊处理
    const isSmartMode = practiceContent.currentMode === 'smart';
    const smartModeText = isSmartMode ? '<p>📅 您的学习进度已保存，系统会在最佳时间提醒您复习。</p>' : '';

    return `
            <div class="result-icon">${passed ? '🎉' : '💪'}</div>
            <h2 class="result-title">${passed ? '练习完成！' : '继续努力！'}</h2>
            <div class="result-score">${score}%</div>

            <div class="result-details">
                <div class="result-detail">
                    <div class="detail-value">${practiceContent.correctAnswers}/${totalQuestions}</div>
                    <div class="detail-label">正确题目</div>
                </div>
                <div class="result-detail">
                    <div class="detail-value">${mode.targetScore}%</div>
                    <div class="detail-label">目标分数</div>
                </div>
                <div class="result-detail">
                    <div class="detail-value">${passed ? '✅' : '❌'}</div>
                    <div class="detail-label">${passed ? '已通过' : '未通过'}</div>
                </div>
            </div>

            <p style="color: #666; margin-bottom: 25px; max-width: 500px; margin-left: auto; margin-right: auto;">
                ${passed ?
            '恭喜你完成了练习！你的表现很棒，已经掌握了这个知识点。' :
            '还需要一些练习来巩固这个知识点。别灰心，重复练习是掌握知识的关键！'
    }
            </p>

            ${smartModeText}

            <div class="result-actions">
                <button class="result-btn btn-retry" onclick="retryPractice()">
                    🔁 重新练习
                </button>
                <button class="result-btn btn-next" onclick="nextKnowledgePoint()">
                    📚 下一个知识点
                </button>
                <button class="result-btn btn-gym" onclick="returnToGym()">
                    🏋️ 返回训练馆
                </button>
            </div>
        `;
  }

  /**
   * 创建错题练习结果HTML
   * @param {number} score - 得分
   * @returns {string} 结果HTML字符串
   */
  function createMistakeResultsHTML(score) {
    const allCorrect = score === 100;

    return `
            <div class="result-icon">${allCorrect ? '🎊' : '📝'}</div>
            <h2 class="result-title">${allCorrect ? '错题全部掌握！' : '错题练习完成'}</h2>
            <div class="result-score">${score}%</div>

            <div class="result-details">
                <div class="result-detail">
                    <div class="detail-value">${practiceContent.correctAnswers}/${practiceContent.mistakeQuestions.length}</div>
                    <div class="detail-label">正确题目</div>
                </div>
                <div class="result-detail">
                    <div class="detail-value">${practiceContent.mistakeQuestions.length}</div>
                    <div class="detail-label">错题数量</div>
                </div>
                <div class="result-detail">
                    <div class="detail-value">${allCorrect ? '✅' : '📚'}</div>
                    <div class="detail-label">${allCorrect ? '全部掌握' : '还需练习'}</div>
                </div>
            </div>

            <p style="color: #666; margin-bottom: 25px; max-width: 500px; margin-left: auto; margin-right: auto;">
                ${allCorrect ?
            '太棒了！你已经完全掌握了之前的错题，可以继续学习新内容了。' :
            '你已经练习了所有错题，但还有一些需要进一步巩固。建议明天再次练习这些题目。'
    }
            </p>

            <div class="result-actions">
                <button class="result-btn btn-retry" onclick="retryMistakePractice()">
                    🔁 再次练习错题
                </button>
                <button class="result-btn btn-next" onclick="startNormalPractice()">
                    🚀 开始正常练习
                </button>
                <button class="result-btn btn-gym" onclick="returnToGym()">
                    🏋️ 返回训练馆
                </button>
            </div>
        `;
  }

  // =============================================================================
  // 导航功能
  // =============================================================================

  /**
   * 重新练习
   * 重置练习状态并重新开始
   */
  function retryPractice() {
    // 隐藏结果区域
    document.getElementById('resultsArea').style.display = 'none';

    // 显示练习区域
    document.getElementById('practiceArea').style.display = 'block';

    // 重置练习状态
    resetPracticeState();

    // 加载第一道题目
    loadCurrentQuestion();

    // 开始计时器
    startPracticeTimer();
  }

  /**
   * 再次练习错题
   */
  function retryMistakePractice() {
    // 重置错题练习状态
    practiceContent.isMistakePractice = true;
    practiceContent.mistakePracticeIndex = 0;
    practiceContent.correctAnswers = 0;

    // 隐藏结果区域
    document.getElementById('resultsArea').style.display = 'none';

    // 显示练习区域
    document.getElementById('practiceArea').style.display = 'block';

    // 重置计时器
    const mode = practiceContent.practiceModes[practiceContent.currentMode];
    practiceContent.timeRemaining = mode.timeLimit;
    practiceContent.practiceActive = true;

    // 加载第一道题目
    loadCurrentQuestion();

    // 开始计时器
    startPracticeTimer();
  }

  /**
   * 开始正常练习
   */
  function startNormalPractice() {
    // 重置为正常练习模式
    practiceContent.isMistakePractice = false;
    practiceContent.currentQuestionIndex = 0;
    practiceContent.correctAnswers = 0;

    // 隐藏结果区域
    document.getElementById('resultsArea').style.display = 'none';

    // 显示练习区域
    document.getElementById('practiceArea').style.display = 'block';

    // 重置练习状态
    resetPracticeState();

    // 加载第一道题目
    loadCurrentQuestion();

    // 开始计时器
    startPracticeTimer();
  }

  /**
   * 学习下一个知识点
   */
  function nextKnowledgePoint() {
    // 在实际项目中，这里会跳转到下一个知识点
    console.log('进入下一个知识点学习');
    alert('即将进入下一个知识点学习');
    // window.location.href = '/learn?pointId=' + (practiceContent.knowledgePoint.id + 1);
  }

  /**
   * 返回训练馆
   */
  function returnToGym() {
    // 在实际项目中，这里会跳转到知识训练馆
    console.log('返回知识训练馆');
    // window.location.href = '/knowledge-gym';
  }
</script>
</body>
</html>